package com.zlx.store.coupon.config;

import com.zlx.store.coupon.constants.RabbitMQConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


import java.util.HashMap;

@Configuration
@Slf4j
public class RabbitConfig {

    private final boolean DURABLE = true;
    private final boolean AUTO_DELETE = false;
    private final boolean EXCLUSIVE = false;

    /**
     * 配置可以转化实体类
     */

    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory factory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(factory);
        rabbitTemplate.setMessageConverter(messageConverter());
        return rabbitTemplate;
    }

    /**
     * 延迟插件配置
     */
    @Bean
    public Queue delayQueue() {
        return new Queue(RabbitMQConstants.DELAY_QUEUE, DURABLE);
    }

    @Bean
    public CustomExchange delayExchange() {

        return new CustomExchange(
                RabbitMQConstants.DELAY_EXCHANGE,
                "x-delayed-message",
                DURABLE,
                AUTO_DELETE,
                new HashMap<String,Object>(){{
                    put("x-delayed-type","direct");
                }}
        );
    }

    @Bean
    public Binding delayBinding(){
        return BindingBuilder
                .bind(delayQueue())
                .to(delayExchange())
                .with(RabbitMQConstants.DELAY_ROUTING_KEY).noargs();
    }
}
